
import json
from abc import abstractmethod
from django.db import connection

from dvadmin.utils.json_response import SuccessResponse, ErrorResponse, DetailResponse
from dvadmin.utils.sqlprocess import query_all_dict, dict_int_change,list_to_dict
from jinjasql import JinjaSql
j = JinjaSql()
from .mysql import MysqlHandel
from .es import ElastSearchHandel
from .mongodb import MongodbHandel
class OnlineHandler:
    def __init__(self,obj,requestdata, id,test=False):
        self.obj = obj
        self.requestdata = requestdata
        self.userid = id

    @abstractmethod
    def sqlprocess(self):
        """
        sql处理
        """
        pass
    @abstractmethod
    def createCursor(self):
        """
        连接数据库，并执行sql
        """
        pass
    @abstractmethod
    def process(self):
        # 获取返回的数据进行处理
        pass


class Mysql(OnlineHandler):
    def __init__(self,obj,requestdata, id,test):
        self.obj = obj
        self.requestdata = requestdata
        self.userid = id
        self.query = None
        self.bind_params =None
        self.newQuery = None
        self.curor = None
        self.test =test
        self.j = JinjaSql()
    def sqlprocess(self):
        self.newQuery = dict_int_change(self.obj['parameter'], self.requestdata, self.userid)
        self.query, self.bind_params = self.j.prepare_query(self.obj['sql'], self.newQuery)
    def createCursor(self):
        self.cursor = connection.cursor()
    def query_all_dict(self,sql, params=None,nopagesql=None):
        rowList = []
        num = 0
        if params:
            num = self.cursor.execute(sql, params=params)
        else:
            mum = self.cursor.execute(sql)
        col_names = [desc[0] for desc in self.cursor.description]
        row = self.cursor.fetchall()
        for list in row:
            tMap = dict(zip(col_names, list))
            rowList.append(tMap)
        if nopagesql:
            if params:
                num = self.cursor.execute(nopagesql, params=params)
            else:
                num = self.cursor.execute(nopagesql)
        self.cursor.close()
        return rowList, col_names, num

    def process(self):
        if self.obj['datatyped'] == 2:
            page = 1
            pagesize = 10
            if self.newQuery.get("page"):
                page = int(self.newQuery["page"])
            if self.newQuery.get("limit"):
                pagesize = int(self.newQuery["limit"])
            pages = (page - 1) * pagesize
            newquery = self.query + " limit " + str(pages) + "," + str(pagesize)
            data, cols_name, num = query_all_dict(newquery, self.bind_params, self.query)
            return {"data": data, 'total': num, 'cols_name': cols_name}

        data, cols_name, num = query_all_dict( self.query,  self.bind_params)
        if self.obj['datatyped'] == 0:
            if self.test:
                return {"data": data,'cols_name':cols_name}
            return data[0]
        elif self.obj['datatyped']  == 1:
            return {"data": data,'cols_name':cols_name}




class OnlineProcess:
    def __init__(self, obj,requestdata, id,test=False):

        """
        data:model对象，或者列表字典4531525
        """
        self.object = None
        self.obj = obj
        self.test = test
        self.requestdata = requestdata
        self.userid = id
        if self.obj['data_source'] == 0:
                self.object = Mysql(self.obj,self.requestdata,self.userid,self.test)
        elif self.obj['data_source'] == 1:
            self.object = MysqlHandel(self.obj, self.requestdata, self.userid, self.test)
        elif self.obj['data_source'] == 2:
            print('mongodb')
            self.object = MongodbHandel(self.obj, self.requestdata, self.userid, self.test)
        elif self.obj['data_source'] == 3:
            # es数据库
            self.object = ElastSearchHandel(self.obj, self.requestdata, self.userid, self.test)

    def get(self):

        # 处理sql
        self.object.sqlprocess()
        # 创建连接器，并执行sql
        self.object.createCursor()
        return self.object.process()

    def post(self):
        pass
    def delete(self):
        pass
    def put(self):
        pass

